<template>
  <div class="host-detail">
    <h1>Host Details</h1>
    <p>Host: {{ hostId }}</p>

    <!-- Offline Message -->
    <div v-if="isOffline" class="offline-message">
      <p>客户端已掉线</p>
    </div>

    <!-- CPU Usage Chart -->
    <div class="chart-container">
      <h2>CPU Usage (%)</h2>
      <div
        id="cpuChart"
        ref="cpuChartRef"
        style="width: 100%; height: 400px"
      ></div>
    </div>

    <!-- Memory Usage Chart -->
    <div class="chart-container">
      <h2>Memory Usage (GB)</h2>
      <div
        id="memoryChart"
        ref="memoryChartRef"
        style="width: 100%; height: 400px"
      ></div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import * as echarts from "echarts";
import { findHostInfo } from "@/api/HostApi.js";

export default {
  setup() {
    const route = useRoute();
    const hostId = ref(route.query.hostId);
    const memoryChartRef = ref(null);
    const cpuChartRef = ref(null);
    let memoryChartInstance = null;
    let cpuChartInstance = null;

    // Data storage
    const timestamps = ref([]); // 时间戳
    const usedMemory = ref([]); // 内存使用量
    const usedCpu = ref([]); // CPU 使用率
    const isOffline = ref(false); // 是否掉线
    const lastCreateTime = ref(null); // 上一次的 createTime
    const noUpdateCount = ref(0); // 记录连续没有更新的次数

    const fetchData = async () => {
      try {
        const result = await findHostInfo(hostId.value);
        if (result.data.code === 1) {
          const data = result.data.data;
          const latestData = data[0];
          const timestamp = new Date(
            latestData.createTime
          ).toLocaleTimeString();
          const memory = parseFloat(
            (latestData.usedMemory / 1024 / 1024 / 1024).toFixed(2)
          );
          const cpu = parseFloat((latestData.usedCpu * 100).toFixed(2)); // Convert to percentage
          if (lastCreateTime.value === latestData.createTime) {
            console.log(
              lastCreateTime.value,
              "   ",
              latestData.createTime,
              "   ",
              noUpdateCount.value
            );
            noUpdateCount.value += 1;
          } else {
            noUpdateCount.value = 0;
          }
          lastCreateTime.value = latestData.createTime;
          if (noUpdateCount.value >= 3) {
            isOffline.value = true;
            clearInterval(intervalId);
            return;
          }
          timestamps.value.push(timestamp);
          usedMemory.value.push(memory);
          usedCpu.value.push(cpu);
          if (timestamps.value.length > 100) {
            timestamps.value.shift();
            usedMemory.value.shift();
            usedCpu.value.shift();
          }

          // Update Memory Chart
          if (!memoryChartInstance) {
            memoryChartInstance = echarts.init(memoryChartRef.value);
          }
          const memoryOption = {
            title: { text: `Memory Usage (${hostId.value})` },
            tooltip: { trigger: "axis" },
            xAxis: { type: "category", data: timestamps.value },
            yAxis: { type: "value", name: "Memory (GB)" },
            series: [
              {
                name: "Used Memory (GB)",
                type: "line",
                data: usedMemory.value,
              },
            ],
          };
          memoryChartInstance.setOption(memoryOption);

          // Update CPU Chart
          if (!cpuChartInstance) {
            cpuChartInstance = echarts.init(cpuChartRef.value);
          }
          const cpuOption = {
            title: { text: `CPU Usage (${hostId.value})` },
            tooltip: { trigger: "axis" },
            xAxis: { type: "category", data: timestamps.value },
            yAxis: { type: "value", name: "CPU Usage (%)" },
            series: [
              {
                name: "CPU Usage (%)",
                type: "line",
                data: usedCpu.value,
              },
            ],
          };
          cpuChartInstance.setOption(cpuOption);
        } else {
          console.error("Error fetching data:", result.data.msg);
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    let intervalId = null;
    onMounted(() => {
      fetchData(); // Initial fetch
      intervalId = setInterval(fetchData, 5000); // Fetch data every 5 seconds
    });

    // Cleanup interval on component unmount
    onUnmounted(() => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    });

    return { hostId, memoryChartRef, cpuChartRef, isOffline };
  },
};
</script>

<style>
.host-detail {
  padding: 20px;
  text-align: center;
}
.chart-container {
  margin-bottom: 40px;
}
#memoryChart,
#cpuChart {
  width: 100%;
  height: 400px;
}
.offline-message {
  color: red;
  font-size: 1.2em;
  margin-bottom: 20px;
}
</style>
